import React, { createContext, useContext, useState } from 'react'
const MyContext = createContext()


export default function ContextDemo({children}) {
  const [person, setPerson] = useState({name:'xia', age: 18})
  const login  = () => console.log('登录')
  const logout = () => console.log('退出')
  const changePerson = (person) => setPerson({...person})

  return (
    <div>
      <h1>Context的使用</h1>
      <MyContext.Provider value={{person, login, logout, changePerson}} children={children} />
    </div>
  )
}

export const Father = ({children}) => {
  const {person:{name, age}} = useContext(MyContext)
 
  return <>
    <h3>父组件</h3>
    <h4>姓名:{name}, 年龄:{age}</h4>
    {children}
  </>
}

export const Child = () => {
  return <>
    <h3>后代组件</h3>
    <MyContext.Consumer>
      {
        value => {
          const {login, logout, changePerson, person:{name, age}} = value
          return <>
                <h4>姓名:{name}, 年龄:{age}</h4>
                <button onClick={login}>登录</button>
                <button onClick={logout}>登出</button>
                <button onClick={() => changePerson({name:'zhou', age: 16})}>换人</button>
          </>
        }
      }
    </MyContext.Consumer>
  </>
}